package com.huc.netty.codec;

import com.huc.netty.core.Header;
import com.huc.netty.core.RpcProtocol;
import com.huc.netty.serial.ISerializer;
import com.huc.netty.serial.SerializerManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author huc
 * @version 1.0
 * @note 编码器
 * @date 2021/9/16 9:52
 */
@Slf4j
public class RpcEncoder extends MessageToByteEncoder<RpcProtocol<Object>> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcProtocol<Object> msg, ByteBuf byteBuf) throws Exception {
        log.info("============开始编码=========");
        Header header=msg.getHeader();
        byteBuf.writeShort(header.getMagic());
        byteBuf.writeByte(header.getSerialType());
        byteBuf.writeByte(header.getReqType());
        byteBuf.writeLong(header.getRequestId());
        ISerializer serializer= SerializerManager.getSerializer(header.getSerialType());
        byte[] data=serializer.serialize(msg.getContent());
        byteBuf.writeInt(data.length);
        byteBuf.writeBytes(data);
        log.info("============编码完成=========");
    }
}
